"""
Created on 24-Sep-2009

@author: dexen
"""

import os
import sys

from PyQt4.QtGui import *            
from PyQt4 import QtCore

import rpyc

import frontend

#===============================================================================
# Schema Dialog
#===============================================================================
class CreateSchemaDialog(QDialog):
    def __init__(self, parent=None):
        super(CreateSchemaDialog, self).__init__(parent)
        self.setGeometry(300,300, 600, 400)
        self.setWindowTitle("Create a New Schema")
        layout = QGridLayout()
        layout.addWidget(QLabel("Schema Name:"), 0, 0)
        self.name_line = QLineEdit()
        layout.addWidget(self.name_line, 0, 1)
        layout.addWidget(QLabel("Schema path:"), 1, 0)
        self.path_line = QLineEdit()
        layout.addWidget(self.path_line, 1, 1)
        
        browse_button = QPushButton("Browse")
        browse_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | 
                                      QDialogButtonBox.Cancel)
        self.connect(button_box, QtCore.SIGNAL("accepted()"), self.on_accept)
        self.connect(button_box, QtCore.SIGNAL("rejected()"), self, 
                     QtCore.SLOT("reject()"))
        
        layout.addWidget(button_box, 2, 1)
        self.connect(browse_button, QtCore.SIGNAL("clicked()"), self.on_browse)
        layout.addWidget(browse_button, 1, 2)
        self.setLayout(layout)
        self.adjustSize()
    
    def on_accept(self):
        schemaname = str(self.name_line.text())
        schemapath = str(self.path_line.text())
        print schemapath, schemaname
        frontend.create_schema(schemaname, schemapath)
        self.close()
        
    def on_browse(self):
        schemapath = QFileDialog.getExistingDirectory(self, 
                "Choose Schema Folder", os.getcwd(), QFileDialog.ShowDirsOnly)
        self.path_line.setText(schemapath)               

    def closeEvent(self, event):
        assert isinstance(event, QCloseEvent)
        print "It is closing"
        event.accept()
        

#===============================================================================
# Schema Panel
#===============================================================================
class TreeWidget(QTreeWidget):
    def __init__(self):
        super(TreeWidget, self).__init__()
        self.setColumnCount(2)
        self.repopulate()
        self.connect(self, QtCore.SIGNAL("itemClicked(QTreeWidgetItem *, int)"),
                     self.on_click)

    def repopulate(self):
        self.top_item = QTreeWidgetItem()
        self.top_item.setText(0, "Schemas")
        self.takeTopLevelItem(0)
        self.addTopLevelItem(self.top_item)
                
        schema_names = frontend.get_schema_names()
        schema_states = frontend.get_schema_states()
        
        for schema_name in schema_names:
            item = QTreeWidgetItem()
            item.setText(0, schema_name)
            self.top_item.addChild(item)
            if schema_states.has_key(schema_name):
                for elem in schema_states[schema_name]:
                    t = QTreeWidgetItem()
                    t.setText(0, elem[0] + ", " + elem[1])
                    item.addChild(t)


    def on_click(self, item, col):
        print "I am clicked", item, col


class SchemaPanel(QWidget):
    def __init__(self, parent):
        super(SchemaPanel, self).__init__()
        self.parent = parent
        self.layout = QGridLayout()
        self.setLayout(self.layout)
        self.tree = TreeWidget()
        self.layout.addWidget(self.tree, 0, 0)
        self.toolbar = QToolBar(self)
        self.layout.addWidget(self.toolbar, 1, 0)
        
        self.minus = self.toolbar.addAction(QIcon("assets/minus.png"), "Delete")
        self.plus = self.toolbar.addAction(QIcon("assets/plus.png"), "Add")
        self.play = self.toolbar.addAction(QIcon("assets/play.png"), "Play")
        self.stop = self.toolbar.addAction(QIcon("assets/stop.png"), "Stop")
        self.refresh = self.toolbar.addAction("Refresh")
        
        self.connect(self.minus, QtCore.SIGNAL("triggered()"), self.on_delete)
        self.connect(self.plus, QtCore.SIGNAL("triggered()"), self.on_add)
        self.connect(self.play, QtCore.SIGNAL("triggered()"), self.on_play)
        self.connect(self.stop, QtCore.SIGNAL("triggered()"), self.on_stop)
        self.connect(self.refresh, QtCore.SIGNAL("triggered()"), self.on_refresh)

        #self.layout.addWidget(QPushButton("HAHA"), 0, 1)   
    
    def _get_level(self, item):
        cnt = 0
        while item != None:
            item = item.parent()
            cnt += 1
        return cnt

    def _get_selected_item(self):
        items = self.tree.selectedItems()
        assert len(items) == 1
        return items[0]
            
    def on_delete(self):    
        item = self._get_selected_item()
        if self._get_level(item) == 2:
            frontend.delete_schema(str(item.text(0)))
            self.tree.repopulate()
            self.tree.expandAll()
    
    def on_add(self):
        item = self._get_selected_item()
        assert isinstance(item, QTreeWidgetItem)
        if self._get_level(item) == 1:
            dialog = CreateSchemaDialog(self)
            dialog.show()
            return
    
    def on_play(self):
        item = self._get_selected_item()
        level = self._get_level(item)
        
        if level == 2:
            pass
        
        
    def on_stop(self):
        pass
    
    def on_refresh(self):
        print "in refresh"
        self.tree.repopulate()
            
    
    
#===============================================================================
# Main Window
#===============================================================================
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("DEXEN Framework")
        self.setGeometry(300, 300, 820, 520)
        self.set_layouts()
        self.create_menu()
        self.create_schema_panel()
    
    def set_layouts(self):
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        self.layout = QGridLayout(central_widget)
    
    def create_schema_panel(self):
        #self.tree = TreeWidget()
        self.schemapanel = SchemaPanel(self)
        self.layout.addWidget(self.schemapanel, 0, 0)
    
    def create_menu(self): 
        self.menubar = QMenuBar(self)
        self.setMenuBar(self.menubar)
        menu = self.menubar.addMenu("Schema")
        assert isinstance(menu, QMenu)
        newSchemaAct = QAction("New", qApp)
        newSchemaAct.setShortcut(QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_N))
        self.connect(newSchemaAct, QtCore.SIGNAL("triggered()"), 
                     self.create_new_schema)
        menu.addAction(newSchemaAct)    
    
    def create_new_schema(self):
        print "Create new schema"
        dialog = CreateSchemaDialog(self)
        dialog.show()
        
#===============================================================================
# Main
#===============================================================================
def main():
    global conn
    frontend.connect()
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())
    
if __name__ == "__main__":
    main()